package com.soledroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.util.Log;

public class AndroidLogin extends Activity  {
	public String IVLE_Token;
	private boolean go = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ivlelogin);        
        
        WebView wv = (WebView) findViewById(R.id.WebViewLogin);                  
        //WebSettings webSettings = wv.getSettings();
        //webSettings.setBuiltInZoomControls(true);
        wv.getSettings().setJavaScriptEnabled(true);
        /* Register a new JavaScript interface called HTMLOUT */
        wv.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
        
        wv.setWebViewClient(new WebViewClient() 
        {               
        	@Override               
        	public void onPageFinished(WebView view, String url) 
        	{     
        		//Log.d("url: " + url, "onPageFinished");
        		// when login is complete, the url will be login_result.ashx?r=0
        		if (url.indexOf("/api/login/login_result.ashx") > 0)
        		{
        			// When login is successful, there will be a &r=0 in the url. It also means the return data is the token itself.
        			if (url.indexOf("&r=0") > 0)
        			{
        				//Log.d("success", "onPageFinished");        				
        				//Log.i("onPageFinished - before loading javascript", "");
        				view.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('body')[0].innerHTML);");        				
        				Intent mIntent = new Intent();
                        //mIntent.putExtras(bundle);
                        setResult(RESULT_OK, mIntent);
        				//view.clearCache(true);
        				//view.destroyDrawingCache();
                        while(!go) {
                        	
                        }
        				finish();
        			}
        		}
        	}
        });
    
        wv.loadUrl("https://ivle.nus.edu.sg/api/login/?apikey=fCxN5zKDDC8ecZtW2jtpy");
    }
    
    final Context myApp = this;

    /* An instance of this class will be registered as a JavaScript interface */
    class MyJavaScriptInterface
    {
        @SuppressWarnings("unused")
        public void processHTML(String html)
        {
        	IVLE_Token = html;
        	
            // process the html as needed by the app
        	SharedPreferences appSettings = getSharedPreferences(SettingsActivity.APP_SETTINGS, MODE_PRIVATE);
        	SharedPreferences.Editor prefEditor = appSettings.edit();
            prefEditor.putString(SettingsActivity.IVLE_TOKEN, IVLE_Token);
            prefEditor.commit();
            
            go = true;
            
        	new AlertDialog.Builder(myApp)  
    	    .setTitle("Token Value")  
    	    .setMessage(IVLE_Token)  
    	    .setPositiveButton(android.R.string.ok, null)  
    	    .setCancelable(false)  
    	    .create() ; 
    	    //.show(); //prompt display for token for checking
        	

			//print out the token or save for next logon or to navigate to next API call.
        	Log.i("Token", IVLE_Token);        	
        }
    }

}